<?php


namespace App\Http\Library;


class Paas
{

    private static $content = [];
    private static $init = false;
    private static $paasUrl;
    private static $appID;
    private static $appKey;


    /**
     * yach通知
     *
     * @param array $arr 通知内容
     */
    public static function yach(array $arr)
    {
        /*服务地址*/
        self::$paasUrl = config('ext.paas_url');
        self::$appID = config('ext.paas_appid');
        self::$appKey = config('ext.paas_appkey');
        /*没有配置则直接返回*/
        if (empty(self::$paasUrl) || empty(self::$appID) || empty(self::$appKey)) {
            return;
        }
        /*回溯跟踪*/
        $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
        $time = date('Y-m-d H:i:s');
        $class = isset($backtrace[1]['class']) ? $backtrace[1]['class'] : '';
        $type = isset($backtrace[1]['type']) ? $backtrace[1]['type'] : '';
        $fun = isset($backtrace[1]['function']) ? $backtrace[1]['function'] : '';
        $traceId = request()->header('X-Trace-Id', Queue::$traceId);
        $backtrace = [
            "[$time]",
            "[$traceId]",
            "[{$backtrace[0]['file']}::{$class}{$type}{$fun}::{$backtrace[0]['line']}]"
        ];
        if (PHP_SAPI !== "cli") {
            /*http*/
            self::$content[] = array_merge($backtrace, $arr);
            /*注册一个请求结束回调函数*/
            self::$init || register_shutdown_function(function() {
                self::shutdown();
            });
            self::$init = true;
        } else {
            self::commit(array_merge($backtrace, $arr));
        }
    }


    /**
     * 触发回调
     */
    private static function shutdown()
    {
        foreach (self::$content as $val) {
            self::commit($val);
        }
        self::$content = [];
    }


    /**
     * 提交结果
     *
     * @param $body
     */
    private static function commit($body)
    {
        $url = sprintf('%s%s', self::$paasUrl, '/project/yach');
        Curl::$url = $url;
        /*请求超过3s记录日志*/
        Curl::$timeOut = 3;
        /*超过5s中断请求*/
        Curl::$timeOutConfine = 1000 * 5;
        $body = [
            'app_id'  => self::$appID,
            'content' => sslEncode($body, self::$appKey)
        ];
        Curl::$requestHeader = [
            'Origin' => config('app.url')
        ];
        Curl::$bodyParam = $body;
        log_arr([
            'url'    => $url,
            'body'   => $body,
            'result' => Curl::commit()
        ], 'paas');
    }

}





/**
 * Paas.php
 *
 * 说明:
 *
 * 修改历史
 * ----------------------------------------
 * 2020/10/14 10:18:00   操作:创建
 **/
